package com.ruoyi.framework.config;

import com.ruoyi.framework.web.service.UserDetailsServiceImpl;
import com.ruoyi.live.base.security.JudgerAuthenticationProvider;
import com.ruoyi.live.base.security.JudgerPasswordEncoder;
import com.ruoyi.live.base.security.JudgerUserDetailServicceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.web.filter.CorsFilter;
import com.ruoyi.framework.config.properties.PermitAllUrlProperties;
import com.ruoyi.framework.security.filter.JwtAuthenticationTokenFilter;
import com.ruoyi.framework.security.handle.AuthenticationEntryPointImpl;
import com.ruoyi.framework.security.handle.LogoutSuccessHandlerImpl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * spring security配置
 *
 * @author ruoyi
 */
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@EnableWebSecurity
@Configuration
@Slf4j
public class SecurityConfig
{
    /**
     * 认证失败处理类
     */
    @Autowired
    private AuthenticationEntryPointImpl unauthorizedHandler;

    /**
     * 退出处理类
     */
    @Autowired
    private LogoutSuccessHandlerImpl logoutSuccessHandler;

    /**
     * token认证过滤器
     */
    @Autowired
    private JwtAuthenticationTokenFilter authenticationTokenFilter;

    /**
     * 跨域过滤器
     */
    @Autowired
    private CorsFilter corsFilter;

    /**
     * 允许匿名访问的地址
     */
    @Autowired
    private PermitAllUrlProperties permitAllUrl;

    @Autowired
    private UserDetailsService userDetailsService;

    private AuthenticationManager authenticationManager;

    /**
     * anyRequest          |   匹配所有请求路径<br/>
     * access              |   SpringEl表达式结果为true时可以访问<br/>
     * anonymous           |   匿名可以访问<br/>
     * denyAll             |   用户不能访问<br/>
     * fullyAuthenticated  |   用户完全认证可以访问（非remember-me下自动登录）<br/>
     * hasAnyAuthority     |   如果有参数，参数表示权限，则其中任何一个权限可以访问<br/>
     * hasAnyRole          |   如果有参数，参数表示角色，则其中任何一个角色可以访问<br/>
     * hasAuthority        |   如果有参数，参数表示权限，则其权限可以访问<br/>
     * hasIpAddress        |   如果有参数，参数表示IP地址，如果用户IP和参数匹配，则可以访问<br/>
     * hasRole             |   如果有参数，参数表示角色，则其角色可以访问<br/>
     * permitAll           |   用户可以任意访问<br/>
     * rememberMe          |   允许通过remember-me登录的用户访问<br/>
     * authenticated       |   用户登录后可访问<br/>
     */
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception
    {
        // 注解标记允许匿名访问的url
        List<RequestMatcher> list = new ArrayList<>();

        permitAllUrl.getUrls().forEach(url -> list.add(new AntPathRequestMatcher(url)));

        String[] staticPath = new String[]{
                // 对于登录login 注册register 验证码captchaImage 允许匿名访问
                "/login", "/register", "/captchaImage", "/judger/login",
                // 静态资源，可匿名访问
                "/", "/*.html", "/**/*.html", "/**/*.css", "/**/*.js", "/profile/**",
                "/v3/**", "/swagger-ui/**", "/swagger-resources/**", "/webjars/**\"", "/*/api-docs", "/druid/**"
        };
        Arrays.stream(staticPath).forEach(url ->  list.add(new AntPathRequestMatcher(url)));

        String[] authenticatedPath = new String[]{
                "/docs/**"
        };

        List<RequestMatcher> authenticatedList = new ArrayList<>();
        Arrays.stream(staticPath).forEach(url ->  authenticatedList.add(new AntPathRequestMatcher(url)));

        httpSecurity.csrf(csrf -> csrf.disable())
                // 禁用HTTP响应标头
                .headers(
                        (headers) -> {
                            headers.cacheControl(Customizer.withDefaults()).disable();
                            headers.frameOptions(Customizer.withDefaults()).disable();
                        }
                )
                // 认证失败处理类
                .exceptionHandling(exception -> exception.authenticationEntryPoint(unauthorizedHandler))
                // 基于token，所以不需要session
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .authorizeHttpRequests(auth -> auth
                    .requestMatchers(list.stream().toArray(AntPathRequestMatcher[]::new)).permitAll()
//                    .requestMatchers(authenticatedList.stream().toArray(AntPathRequestMatcher[]::new)).authenticated()
                    // 除上面外的所有请求全部需要鉴权认证
                    .anyRequest().authenticated()
                );

        // 添加Logout filter
        httpSecurity.logout(logout -> logout.logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler));
        // 添加JWT filter
        httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        // 添加CORS filter
        httpSecurity.addFilterBefore(corsFilter, JwtAuthenticationTokenFilter.class);
        httpSecurity.addFilterBefore(corsFilter, LogoutFilter.class);

        httpSecurity.authenticationManager(this.authenticationManager);

        return httpSecurity.build();
    }

    /**
     * 解决 无法直接注入 AuthenticationManager
     *
     * @return
     * @throws Exception
     */
    @Bean
    public AuthenticationManager defaultAuthenticationManager() {
        if (this.authenticationManager == null) {
            DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider(new BCryptPasswordEncoder());
            daoAuthenticationProvider.setUserDetailsService(userDetailsService);
            JudgerAuthenticationProvider judgerAuthenticationProvider = new JudgerAuthenticationProvider(new JudgerPasswordEncoder());
            judgerAuthenticationProvider.setUserDetailsService(new JudgerUserDetailServicceImpl());
            this.authenticationManager = new ProviderManager(daoAuthenticationProvider, judgerAuthenticationProvider);
        }

        return authenticationManager;
    }

    @Bean
    public UserDetailsService userDetailsService() {
        return new UserDetailsServiceImpl();
    }
}